import React, {useState} from 'react';
import {useRecoilState, useSetRecoilState} from 'recoil';

import {todoListState,demoNum,showDemoNum} from './Todo_state';

export const TodoItemCreator = () => {

  const [inputValue, setInputValue] = useState('');
  const setTodoList = useSetRecoilState(todoListState);
  const [getDemoNum,setDemoNum] = useRecoilState(demoNum);
  // const setDemoNum = useSetRecoilState(demoNum); //也可以
  const [getShowDemoNum,setShowDemoNum] = useRecoilState(showDemoNum);

  const addItem = () => {
    setTodoList(oldTodoList => [
      ...oldTodoList,
      {
        id: getId(),
        text: inputValue,
        isComplete: false,
      }
    ]);
    setInputValue('');

    setShowDemoNum(val => {
      console.log("setShowDemoNum",val);
      let num = val.val;
      return num+1  
    });
  };

  const addAtom = () =>{
    setDemoNum(val =>{
      console.log(val);
      return val+100
    });
  }

  const onChange = ({target: {value}}) => {
    setInputValue(value);
  };

  return (
    <div>
      <input type="text" value={inputValue} onChange={onChange} />
      <button onClick={addItem}>Add</button>
      <button onClick={addAtom}>Add</button>
    </div>
  );
};

// utility for creating unique Id
let id = 0;
function getId() {
  return id++;
}
